package com.qiaofang.common.interceptor;

import com.qiaofang.common.constant.CommonConstant;
import com.qiaofang.common.exception.NotLoginException;
import com.qiaofang.common.utils.Context;
import com.qiaofang.common.utils.StringUtil;
import com.qiaofang.common.utils.Token;
import com.qiaofang.common.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader(CommonConstant.CONSTANT_TOKEN_HEADER_NAME);
        log.info(header);
        if (StringUtil.isNotBlank(header)) {
            Token token = (Token) TokenUtil.getToken(header);
            if (token != null) {
                Context context = new Context(token.getUserId(), token.getUserUuid(), header);
                Context.setThreadLocal(context);
                return true;
            }
        }
//        return true;
        throw new NotLoginException();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Context.removeContextThreadLocal();
    }
}
